package com.sale.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.RemoteUnitService;
import com.sale.system.api.domain.dto.MaterialAuxiliaryDto;
import com.sale.system.api.model.MaterialUnitDto;
import com.sale.system.domain.*;
import com.sale.system.domain.dto.MaterialHalfDto;
import com.sale.system.domain.dto.SysCategoryDto;
import com.sale.system.domain.dto.SysTheDropDto;
import com.sale.system.domain.vo.MaterialAlarmVo;
import com.sale.system.domain.vo.MaterialHalfVo;
import com.sale.system.domain.vo.MaterialMqMessageVo;
import com.sale.system.mapper.*;
import com.sale.system.service.IMaterialHalfService;
import com.sale.system.service.ISysCategoryService;
import com.sale.system.service.ISysDocumentService;
import com.sale.system.service.ISysMidSplitService;
import com.sale.system.util.MaterialMqUtil;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 半成品实现类
 * @Date 23-12-06
 * @Author hl
 **/
@RequiredArgsConstructor
@Service
public class MaterialHalfServiceImpl implements IMaterialHalfService {

    private final MaterialHalfMapper materialHalfMapper;

    private final MaterialAuxiliaryMapper materialAuxiliaryMapper;

    private final SysAuxiliaryUnitMapper sysAuxiliaryUnitMapper;

    private final ISysDocumentService sysDocumentService;

    private final SysAuxiliaryUnitDetailMapper sysAuxiliaryUnitDetailMapper;

    private final MaterialRawServiceImpl materialRawServiceImpl;

    private final SysTheAlarmMapper sysTheAlarmMapper;

    @DubboReference
    RemoteUnitService remoteUnitService;

    private final ISysCategoryService sysCategoryService;

    private final ISysMidSplitService sysMidSplitService;

    /**
     * 获取半成品配置
     */
    @Override
    public TableDataInfo<MaterialHalfDto> selectHalfList(MaterialHalfVo materialHalfVo, PageQuery pageQuery) {
        Page<MaterialHalfDto> page = materialHalfMapper.selectHalfList(pageQuery.build(), this.buildQueryWrapper(materialHalfVo));
        List<MaterialHalfDto> list = page.getRecords();
        //渲染辅助属性
//        // 多单位
//        List<SysTheDropDto> listThe = sysAuxiliaryUnitMapper.selectMultiMeteringUnitAllList();
//        Map<String, String> map = listThe.stream()
//            .collect(Collectors.toMap(SysTheDropDto::getValue, SysTheDropDto::getLabel));

        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();
        for (MaterialHalfDto dto :
            list) {
            //String unit = dto.getMaterialUnit();
          //  if (unit != null) {
              //  dto.setMaterialUnitDict(unitByCodeToMap.get(unit).getUnitName());
           // }
            dto.setAuxiliaryAttribute(materialAuxiliaryMapper.selectAuxiliaryById(dto.getMaterialId()));
        }
        return TableDataInfo.build(page);
    }

    private Wrapper<MaterialHalfVo> buildQueryWrapper(MaterialHalfVo materialHalfVo) {
        QueryWrapper<MaterialHalfVo> wrapper = Wrappers.query();
        wrapper
            .like(ObjectUtil.isNotNull(materialHalfVo.getMaterialCode()), "t1.material_code", materialHalfVo.getMaterialCode())
            .like(StringUtils.isNotBlank(materialHalfVo.getMaterialName()), "t1.material_name", materialHalfVo.getMaterialName())
            .eq(StringUtils.isNotBlank(materialHalfVo.getMaterialStatus()),"t1.material_status",materialHalfVo.getMaterialStatus())
            .eq(StringUtils.isNotNull(materialHalfVo.getMaterialType()), "t1.material_type", materialHalfVo.getMaterialType()).between(materialHalfVo.getStartTime() != null && materialHalfVo.getEndTime() != null,
                "t1.create_time", materialHalfVo.getStartTime(), materialHalfVo.getEndTime());
        return wrapper;
    }

    /**
     * 新增半成品
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMaterialHalf(MaterialHalfVo materialHalfVo) throws Exception {
        MaterialHalf half = new MaterialHalf();
        BeanUtils.copyProperties(materialHalfVo, half);
        half.setMaterialId(IdWorker.getId());
        List<SysAuxiliaryUnitDetail> list2 = materialHalfVo.getList();
        StringBuffer moreUnit = new StringBuffer();
        for (SysAuxiliaryUnitDetail item: list2) {
            moreUnit.append(item.getAuxiliaryId()).append(",");
            item.setMaterialId(half.getMaterialId());
        }
        half.setMaterialMoreUnit(moreUnit.toString().substring(0,moreUnit.length()-1));
        //半成品编码按照类别配置中得生成
        SysCategoryDto sysCategoryDto = sysCategoryService.selectCategoryById(materialHalfVo.getMaterialType());
        String s = sysMidSplitService.selectSplitStr(sysCategoryDto.getCodeRule());
        if (StringUtils.isEmpty(s)) {
            throw new GlobalException("编码生成失败，请检查配置");
        }
        half.setMaterialCode(s);
        half.setCreateBy(LoginHelper.getUsername());
        int ins = materialHalfMapper.insert(half);
        if (ins > 0) {
            if (materialHalfVo.getAlarmCode() != null) {
                List<SysTheAlarm> list = materialRawServiceImpl.alarmConfiguration(materialHalfVo.getAlarmCode());
                long op = half.getMaterialId();
                String matetialCode = half.getMaterialCode();
                for (SysTheAlarm sysTheAlarm : list) {
                    String roles = "";
                    for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {
                        roles = roles + sysTheAlarm.getRoleIds().get(i);
                        if (sysTheAlarm.getRoleIds().size() - 1 != i) {
                            roles = roles + ",";
                        }
                    }
                    sysTheAlarm.setAlarmRoleId(roles);
                    sysTheAlarm.setAlarmAssociatedId(op);
                    sysTheAlarm.setAlarmOfMaterial(3);
                    sysTheAlarm.setAlarmMaterialCode(matetialCode);
                }
                if (list.size() != 0) {
                    ins = sysTheAlarmMapper.insertSysTheAlarm(list);
                }
            }
            if (ins == 0) {
                throw new SQLException("抛出异常");
            }
        }
        //mq发送消息
        String userIdStr = LoginHelper.getUserIdStr();
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        BeanUtils.copyProperties(half, materialMqVo);
        materialMqVo.setUserIdStr(userIdStr);
        materialMqVo.setMaterialType(half.getMaterialType());
        materialMqVo.setMaxInventory(String.valueOf(half.getMaterialMinSecurity()));
        MaterialMqUtil.materialMqSend(materialMqVo);

        List<MaterialAuxiliary> list = materialHalfVo.getAuxiliaryAttribute();
        if (list != null) {
            for (MaterialAuxiliary auxiliary :
                list) {
                auxiliary.setMaterialId(half.getMaterialId());
                auxiliary.setAuxiliaryId(IdWorker.getId());
            }
            materialAuxiliaryMapper.insertBatch(list);
        }
        if(list2.get(0).getAuxiliaryId()!=null){
            sysAuxiliaryUnitDetailMapper.insertBatch(list2);
        }
        return ins;
    }

    /**
     * 删除半成品
     */
    @Override
    public int deleteMaterialHalf(String materialId) throws Exception {
        String[] materialIdS = materialId.split(",");
        ArrayList<String> arrayList = new ArrayList<>();
        for (String str :
            materialIdS) {
            arrayList.add(str);
            //删除对应属性
            HashMap<String, Object> map = new HashMap<>();
            map.put("material_id", str);
            materialAuxiliaryMapper.deleteByMap(map);
            sysAuxiliaryUnitDetailMapper.deleteByMap(map);
        }
        //mq发送消息(删除)
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        materialMqVo.setIdStr(materialId);
        MaterialMqUtil.materialMqSendDelete(materialMqVo);
        return materialHalfMapper.deleteBatchIds(Arrays.asList(materialIdS));
    }

    /**
     * 查询单个半成品
     */
    @Override
    public MaterialHalfDto selectMaterialHalfById(long materialId) {
        MaterialHalfDto dto = new MaterialHalfDto();
        MaterialHalf half = materialHalfMapper.selectById(materialId);
        BeanUtils.copyProperties(half, dto);
        List<MaterialAuxiliaryDto> list = materialAuxiliaryMapper.selectAuxiliaryById(materialId);
        Map<String, Object> map = new HashMap<>();
        map.put("material_id",materialId);
        List<SysAuxiliaryUnitDetail> list1 = sysAuxiliaryUnitDetailMapper.selectByMap(map);
        //告警信息数据
        int alarmOfMaterial = 3;
        List<SysTheAlarm> theList = sysTheAlarmMapper.selectSysTheAlarmList(materialId, alarmOfMaterial);
        MaterialAlarmVo materialAlarmVo = materialRawServiceImpl.alarmConfigtType(theList);
        dto.setAlarmCode(materialAlarmVo);
        dto.setAuxiliaryAttribute(list);
        dto.setList(list1);
        return dto;
    }

    /**
     * 修改半成品
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMaterialHalfEdit(MaterialHalfVo materialHalfVo) throws Exception {
        MaterialHalf half = new MaterialHalf();
        BeanUtils.copyProperties(materialHalfVo, half);
        List<SysAuxiliaryUnitDetail> list2 = materialHalfVo.getList();
        StringBuffer moreUnit = new StringBuffer();
        for (SysAuxiliaryUnitDetail item: list2) {
            moreUnit.append(item.getAuxiliaryId()).append(",");
            item.setMaterialId(half.getMaterialId());
        }
        if (list2.size()>0){
            half.setMaterialMoreUnit(moreUnit.toString().substring(0,moreUnit.length()-1));
        }

        int ors = materialHalfMapper.updateById(half);
        if (ors > 0) {
            long materialId = materialHalfVo.getMaterialId();
            sysTheAlarmMapper.deleteSysTheAlarmOnById(materialId);
            if (ors > 0) {
                long sy = materialHalfVo.getMaterialId();
                String materialCode = materialHalfVo.getMaterialCode();
                List<SysTheAlarm> list = materialRawServiceImpl.alarmConfiguration(materialHalfVo.getAlarmCode());
                for (SysTheAlarm sysTheAlarm :
                    list) {

                    String roles = "";
                    for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {

                        roles = roles + sysTheAlarm.getRoleIds().get(i);
                        if (sysTheAlarm.getRoleIds().size() - 1 != i) {
                            roles = roles + ",";
                        }

                    }

                    sysTheAlarm.setAlarmRoleId(roles);

                    sysTheAlarm.setAlarmAssociatedId(sy);
                    sysTheAlarm.setAlarmOfMaterial(3);
                    sysTheAlarm.setAlarmMaterialCode(materialCode);
                }
                if (list.size() != 0) {
                    ors = sysTheAlarmMapper.insertSysTheAlarm(list);
                }
                if (ors == 0) {
                    throw new SQLException("抛出异常");
                }
            } else {
                throw new SQLException("抛出异常");
            }
        }
        //mq发送消息
        String userIdStr = LoginHelper.getUserIdStr();
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        BeanUtils.copyProperties(half, materialMqVo);
        materialMqVo.setUserIdStr(userIdStr);
        materialMqVo.setMaterialType(Long.parseLong(String.valueOf(half.getMaterialType())));
        materialMqVo.setMaxInventory(String.valueOf(half.getMaterialMinSecurity()));
        MaterialMqUtil.materialMqSend(materialMqVo);
        List<MaterialAuxiliary> list = materialHalfVo.getAuxiliaryAttribute();
        if (list != null) {
            //删除对应属性
            HashMap<String, Object> map = new HashMap<>();
            long materialId = half.getMaterialId();
            map.put("material_id", materialId);
            materialAuxiliaryMapper.deleteByMap(map);
            sysAuxiliaryUnitDetailMapper.deleteByMap(map);
            //重新新增对应属性
            for (MaterialAuxiliary auxiliary :
                list) {
                auxiliary.setMaterialId(materialId);
            }
            //批量新增物料属性信息
            materialAuxiliaryMapper.insertBatch(list);
        }
        if (list2.size()>0){
            if(list2.get(0).getAuxiliaryId()!=null){
                sysAuxiliaryUnitDetailMapper.insertBatch(list2);
            }
        }

        return ors;
    }

    /**
     * 冻结
     */
    @Override
    public int updateEditFreeze(Long materialId) {
        MaterialHalf half = new MaterialHalf();
        half.setMaterialStatus(1);
        half.setMaterialId(materialId);
        return materialHalfMapper.updateById(half);
    }

    /**
     * 成品解结
     */
    @Override
    public int updateEditThaw(Long materialId) {
        MaterialHalf half = new MaterialHalf();
        half.setMaterialStatus(2);
        half.setMaterialId(materialId);
        return materialHalfMapper.updateById(half);
    }

}
